package com.evaluation.security;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.evaluation.dao.config.EvalJdbcTemplate;


@Component
public class LdapAuthProvider extends EvalJdbcTemplate implements AuthenticationProvider {
	private Logger log = LoggerFactory.getLogger(LdapAuthProvider.class);
	
	//@Value("${ldap.login.url}")
	//private String loginUrl;
	
	/// @Resource
	///private LdapTemplate ldapTemplate;

	//@Resource
	//private ContextSource contextSource;
	
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {

		/**
		AndFilter filter = new AndFilter();
		filter.and(new EqualsFilter("objectclass", "person"))
				.and(new EqualsFilter("sAMAccountName", (String) authentication.getPrincipal()));

		boolean isLogin = ldapTemplate.authenticate("", filter.encode(), (String) authentication.getCredentials() );
		**/
		//System.out.println( md5.encodePassword(authentication.getPrincipal().toString(), authentication.getCredentials().toString()) );
		
		Map<String, Object> map = null;
		
		try {
			map = jdbc.getJdbcTemplate().queryForMap("select * from tb_userinfo where user_id=? and status='1'", authentication.getPrincipal());
		}
		catch( EmptyResultDataAccessException e ) {
			throw new UsernameNotFoundException("用户名或密码错误");
		}
		
		log.info("{}", map);

		String[] roles = ((String)map.get("role_id")).split(",");
		for ( int i=0; i<roles.length; i++ ) {
			roles[i] = "ROLE_"+roles[i];
		}
		
		PwdEncoder md5 = new Md5PwdEncoder();
		String password = (String)map.get("password");
		
		///if( StringUtils.hasText(password) ) {
			if( password.equals( md5.encodePassword(authentication.getCredentials().toString(), authentication.getPrincipal().toString())) ) {
				
				return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(),
						AuthorityUtils.createAuthorityList( roles ) );
			}
			else {
				throw new UsernameNotFoundException("用户名或密码错误");
			}
		///}
		
		// 返回一个Token对象表示登陆成功
		///return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(),
		///		AuthorityUtils.createAuthorityList( roles ) );

	}
/*
	@Bean("ldapContextSource")
	@ConfigurationProperties(prefix = "ldap.context-source")
	public LdapContextSource ldapContextSource() {
		//ldapContextSource = new LdapContextSource();

		
		return new LdapContextSource();
	}
	
	@Bean
	public LdapTemplate ldapTemplate( LdapContextSource ldapContextSource ) {
		// LdapTemplate lt = new LdapTemplate( ldapContextSource );

		ldapTemplate = new LdapTemplate(ldapContextSource);

		return ldapTemplate;
	}
*/
	/*
	 * private final static class DnContextMapper extends
	 * AbstractContextMapper<String> {
	 * 
	 * @Override protected String doMapFromContext(DirContextOperations ctx) { //
	 * TODO Auto-generated method stub return ctx.getNameInNamespace(); }
	 * 
	 * }
	 */

	@Override
	public boolean supports(Class<?> aClass) {
		return true;
	}
}